package com.cheng.xbsc.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;


@Configuration
public class SpringRedisConfig {

    //声明bean的名字为redisTemplate
    @Bean("redisTemplate")
    public RedisTemplate<Object, Object> getRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);//设置连接工厂对象

        StringRedisSerializer keyRedisSerializer = new StringRedisSerializer();
        GenericJackson2JsonRedisSerializer valueRedisSerializer = new GenericJackson2JsonRedisSerializer();

        redisTemplate.setKeySerializer(keyRedisSerializer);//设置key的序列化器，使用String序列化器，默认以UTF-8对key进行编码和解码
        redisTemplate.setValueSerializer(valueRedisSerializer);//设置value的序列化器，该序列化器会自动将对象类型作为其中转换的一个key和value存入json中

        //设置hash类型
        redisTemplate.setHashKeySerializer(keyRedisSerializer);
        redisTemplate.setHashValueSerializer(valueRedisSerializer);

        return redisTemplate;
    }

}
